#include "CustomItemDelegrate.h"

CustomItemDelegrate::CustomItemDelegrate(const QRegExp& regExp,QObject* parent) : QStyledItemDelegate(parent)
{
    m_regExp = regExp;
}

CustomItemDelegrate::~CustomItemDelegrate(void)
{
}

QWidget* CustomItemDelegrate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    //创建带有正则表达式的输入框
    Q_UNUSED(option);
    Q_UNUSED(index);
    QLineEdit* editor = new QLineEdit(parent);
    editor->setValidator(new QRegExpValidator(m_regExp, parent));
    return editor;
}

void CustomItemDelegrate::setEditorData(QWidget* editor, const QModelIndex& index) const
{
    QString text = index.model()->data(index, Qt::EditRole).toString();
    QLineEdit* lineEdit = qobject_cast <QLineEdit*>(editor);
    lineEdit->setText(text);
}

void CustomItemDelegrate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const
{
    QLineEdit* lineEdit =  qobject_cast<QLineEdit*>(editor);
    QString text = lineEdit->text();
    model->setData(index, text, Qt::EditRole);
}
